import React, { useState } from 'react'
import { Modal, Upload } from 'antd'
import { RcFile, UploadFile, UploadProps } from 'antd/es/upload'
import { uploadFiles } from '../api/upload'
import { PlusOutlined } from '@ant-design/icons'

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result as string)
        reader.onerror = (error) => reject(error)
    })
// interface AppImageUploadProps extends UploadProps{
//
// }
const ImageUpload: React.FC<UploadProps> = (props) => {
    // maxCount - 父组件传入的上传图片数量的最大值, 可控制单张或多张图片
    // disabled - 父组件传入的控制组件是否禁止上传
    // handleMediaResource - 与父组件进行数据通信

    const { maxCount = 3, disabled } = props
    const [previewOpen, setPreviewOpen] = useState(false)
    const [previewImage, setPreviewImage] = useState('')
    const [previewTitle, setPreviewTitle] = useState('')
    const [fileList, setFileList] = useState<UploadFile[]>([])
    const handleCancel = () => setPreviewOpen(false)

    // 父组件提交数据时, 重置该子组件数据
    // useImperativeHandle(ref, () => ({ clearUploadList }))
    // const clearUploadList = () => {
    //     setFileList([])
    // }

    // 是否允许显示删除按钮
    // 只读时, 不允许用户进行删除操作
    const showUploadList = { showRemoveIcon: disabled ? false : true }

    // 图片点击放大查看
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile)
        }

        setPreviewImage(file.url || (file.preview as string))
        setPreviewOpen(true)
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1))
    }
    const handleChange = () => {
    }

    // base64转Blob
    // const base64ToBlob = (code: string) => {
    //     const parts = code.split(';base64,')
    //     const contentType = parts[0].split(':')[1]
    //     const raw = window.atob(parts[1])
    //     const rawLength = raw.length
    //     const uInt8Array = new Uint8Array(rawLength)
    //     for (let i = 0; i < rawLength; ++i) {
    //         uInt8Array[i] = raw.charCodeAt(i)
    //     }
    //     return new Blob([uInt8Array], { type: contentType })
    // }

    // 自定义上传逻辑
    const customRequest: UploadProps['customRequest'] = async (options) => {
        const file = options.file as RcFile
        // uploadFunc 是服务器上传操作
        const base64 = await getBase64(file as RcFile)
        const formData = new FormData()
        formData.append('file', file)
        try {
            const res = await uploadFiles(formData)
            const newImgList = [
                ...fileList,
                {
                    uid: file.uid,
                    name: file.name,
                    status: 'done',
                    url: res.accessUrl,
                    // url: URL.createObjectURL(base64ToBlob(base64)),
                    lastModified: file.lastModified,
                    lastModifiedDate: file.lastModifiedDate,
                    originFileObj: file,
                    percent: 100,
                    thumbUrl: base64,
                    type: file.type,
                } as UploadFile,
            ]
            setFileList(newImgList)
            // console.log(file)

        } catch (error) {
            const newFileList = [
                ...fileList,
                {
                    uid: file.uid,
                    name: file.name,
                    status: 'error',
                    lastModified: file.lastModified,
                    lastModifiedDate: file.lastModifiedDate,
                    originFileObj: file,
                    percent: 100,
                    type: file.type,
                } as UploadFile,
            ]
            setFileList(newFileList)
        }
    }

    const onRemove = (file: UploadFile) => {
        const index = fileList.indexOf(file)
        const newFileList = fileList.slice()
        newFileList.splice(index, 1)
        setFileList(newFileList)
    }

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    )
    const AppUpload = <Upload
        {...props}
        listType="picture-card"
        fileList={fileList}
        showUploadList={showUploadList}
        onPreview={handlePreview}
        onChange={handleChange}
        onRemove={onRemove}
        customRequest={customRequest}
    >
        {fileList.length >= maxCount ? null : uploadButton}
    </Upload>
    const PreviewModal = <Modal
        centered
        width={700}
        // 注意 : 这儿3.x展示modal属性是visible,5.x是open
        open={previewOpen}
        title={previewTitle}
        footer={null}
        onCancel={handleCancel}
    >
        <img
            alt="example"
            style={{
                width: '100%',
            }}
            src={previewImage}
        />
    </Modal>
    return <>
        {AppUpload}
        {PreviewModal}

    </>

}

export default ImageUpload

